const express = require('express');
const jwt = require('jsonwebtoken');
const authenticateToken = require('../middleware/auth');
const router = express.Router();

// 获取用户信息
router.get('/profile', authenticateToken, (req, res) => {
  const userId = req.user.userId;
  
  const query = 'SELECT id, phone, username, email, avatar, created_at FROM users WHERE id = ?';
  
  global.db.query(query, [userId], (err, results) => {
    if (err) {
      console.error('获取用户信息失败:', err);
      return res.status(500).json({ message: '获取用户信息失败' });
    }
    
    if (results.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    const user = results[0];
    res.json({
      message: '获取成功',
      user: {
        id: user.id,
        phone: user.phone,
        username: user.username,
        email: user.email || '',
        avatar: user.avatar || 'avatar1',
        createdAt: user.created_at
      }
    });
  });
});

// 更新用户信息 - 支持用户名和头像
router.put('/updateProfile', authenticateToken, (req, res) => {
  const userId = req.user.userId;
  const { username, avatar } = req.body;
  
  console.log('收到更新请求:', { username, avatar, userId });
  
  // 构建动态更新字段
  let updateFields = [];
  let updateValues = [];
  
  if (username !== undefined && username.trim() !== '') {
    updateFields.push('username = ?');
    updateValues.push(username.trim());
  }
  
  if (avatar !== undefined && avatar.trim() !== '') {
    updateFields.push('avatar = ?');
    updateValues.push(avatar.trim());
  }
  
  if (updateFields.length === 0) {
    return res.status(400).json({ message: '没有要更新的字段' });
  }
  
  updateValues.push(userId);
  const query = `UPDATE users SET ${updateFields.join(', ')} WHERE id = ?`;
  
  console.log('执行更新SQL:', query, updateValues);
  
  global.db.query(query, updateValues, (err, result) => {
    if (err) {
      console.error('更新用户信息失败:', err);
      return res.status(500).json({ message: '更新失败' });
    }
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    console.log('更新成功，影响行数:', result.affectedRows);
    res.json({ message: '更新成功' });
  });
});

module.exports = router;


